// pages/goods_list/goods_list.js
Page({
  data: {
    tab:[
      {title:"综合",isactive:true},
      {title:"销量",isactive:false},
      {title:"价格",isactive:false},
    ],
    activeIndex:0,
    goodsList:[]
  },
  // 总页数
  totalPage:1,
  // 请求需要数据
  Params:{
    query:"",
    cid:"",
    pagenum:1,
    pagesize:10
  },
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
      mask:true
    });
    this.Params.cid = options.cat_id;
    wx.request({
      url: 'https://api-hmugo-web.itheima.net/api/public/v1/goods/search',
      data: this.Params,
      success:(res)=>{
        this.setData({goodsList:res.data.message.goods});
        // 计算总页数
        this.totalPage = Math.ceil(res.data.message.total / 10);
        wx.hideLoading();
      }
    })
  },
  tabClick(data){
    const {index} = data.detail;
    this.setData({activeIndex:index})
  },
  // 页面触底时触发
  onReachBottom(){
    // 判断是否已经最后一页
    if (this.Params.pagenum >= this.totalPage) {
      wx.showToast({
        title: '没有更多了',
        icon: 'none',
      })
    }else{
      wx.showLoading({
        title: '加载中',
        mask:true
      }),
      // 获取下一页
      this.Params.pagenum += 1;
      wx.request({
        url: 'https://api-hmugo-web.itheima.net/api/public/v1/goods/search',
        data: this.Params,
        success:(res)=>{
          // 拼接商品数组（上一页+这一页）
          let list = [...this.data.goodsList,...res.data.message.goods]
          this.setData({goodsList:list});
          wx.hideLoading();
        }
      })
    }
  },
  // 下拉刷新
  onPullDownRefresh(){
    wx.showLoading({
      title: '加载中',
      mask:true
    });
    this.Params.pagenum = 1;
    this.setData({goodsList:[]});
    wx.request({
      url: 'https://api-hmugo-web.itheima.net/api/public/v1/goods/search',
      data: this.Params,
      success:(res)=>{
        this.setData({goodsList:res.data.message.goods});
        this.totalPage = Math.ceil(res.data.message.total / 10);
        wx.hideLoading();
        // 停止下拉动画
        wx.stopPullDownRefresh()
      }
    })
  }  
})